gpNamespace.GamePlayLayer = cc.Layer.extend({
    sprite: null,
    orderedPlayers: [],
    currentAt: null,
    currentAtIndex: 0,
    holdAt: null,            //操作停顿 默认自己
    currentChuTile: null,    //当前打的牌
    zhuangIndex: 0,
    playStatus: 0,
    timeLayer: null,
    lastChuPlayer: null,
    lastChuType: null,

    mpClicked: false,

    armature: null,
    dipai: null,
    mingPaiMenu: null,

    missionOutMenu: null,
    missionInMenu: null,
    missionSprite: null,
    isHide: false,
    self: null,

    added: false,

    ctor: function (orderedPlayers) {
        this.orderedPlayers = orderedPlayers;
        this.zhuangIndex = -1;
        this.currentChuTile = null;
        this.lastChuPlayer = null;

        this.mpClicked = false;
        this.self = this;

        this._super();
        this.init();
    },

    init: function () {
    	cc.spriteFrameCache.addSpriteFrames(gpNamespace.tileRes.Game_tile_plist);
    	
        if (gpNamespace.subRoom < 5)
            this.addInnerMission();

        var tyNet = gpNamespace.TyNetManager.getInstance();
        tyNet.innerMissionRewardTimes = 0;
        tyNet.setGameLayer(this);
        //-----------------------------------------------------------------------

        cc.log("add timeLayer");
        this.timeLayer = new gpNamespace.TimerLayer(20);
        this.addChild(this.timeLayer, 10);

        //玩家之间的切换
        for (var i = 0; i < this.orderedPlayers.length; i++) {
            var player = this.orderedPlayers[i];
            
            cc.log("player:" + player + ",i:" + i);
            cc.log("player.orderIndex" +player.orderIndex);
            switch (player.orderIndex) {
                case tyNamespace.OrderIndex.ZiJi:
                    this.addChild(new gpNamespace.MyTilesLayer(player, this), 2);
                    break;
                case tyNamespace.OrderIndex.Xia:
                    this.addChild(new gpNamespace.NextPlayerTilesLayer(player, this), 1);
                    break;
              /*  case tyNamespace.OrderIndex.Dui:
                	this.addChild(new gpNamespace.OppPlayerTilesLayer(player, this), 1);
                    break;*/
                case tyNamespace.OrderIndex.Shang:
                	this.addChild(new gpNamespace.PrePlayerTilesLayer(player, this), 1);
                	break;
                default:
                    break;
            }
        }

        var tyNet = gpNamespace.TyNetManager.getInstance();
        tyNet.setDdzGameLayer(this);
        
        var goodIconName = "#cdd_xtk_wjxx_004u.png";//"#icon_prop_" + str + "u.png";

        goodIcon = new cc.Sprite(goodIconName);
        goodIcon.setPosition(this.getPlayerByOrderIndex(2).playLayer.headArmaturePoint);
        this.addChild(goodIcon, 300);
    },

    addInnerMission: function () {
        //任务出来
//        var missionOutItem = new cc.MenuItemImage(gpNamespace.mission.Mission_out, gpNamespace.mission.Mission_out, this.missionOutCallbackFunction, this);
//        missionOutItem.attr({
//            x: 41 / 2,
//            y: 75 / 2
//        });
//        var missionOutMenu = new cc.Menu(missionOutItem);
//        missionOutMenu.attr({
//            x: 0,
//            y: 630
//        });
//        this.addChild(missionOutMenu, 3000);
//        missionOutMenu.setVisible(false);
//        this.missionOutMenu = missionOutMenu;
//
//        //任务进去
//        var missionInItem = new cc.MenuItemImage(gpNamespace.mission.Mission_in, gpNamespace.mission.Mission_in, this.missionInCallbackFunction, this);
//        missionInItem.attr({
//            x: 41 / 2,
//            y: 75 / 2
//        });
//        var missionInMenu = new cc.Menu(missionInItem);
//        missionInMenu.attr({
//            x: 264,
//            y: 630
//        });
//        this.addChild(missionInMenu, 3000);
//        this.missionInMenu = missionInMenu;
//
//        //任务牌
//        var missionSprite = new cc.Sprite(gpNamespace.mission.Mission_renwupai);
//        missionSprite.attr({
//            x: 0,
//            y: 584,
//            anchorX: 0,
//            anchorY: 0
//        });
//        this.addChild(missionSprite, 3000);
//        this.missionSprite = missionSprite;

    },
    
    setXuezhanInfo: function () {
    	//cc.log(xzgbNamespace.UsePropBeforeInfo.GOODID);
    	//cc.log(xzgbNamespace.UsePropBeforeInfo.GOODPRICE);
    	//cc.log(xzgbNamespace.UsePropBeforeInfo.GOODPRICETYPE);
    	//cc.log(xzgbNamespace.UsePropBeforeInfo.GOODRESTCOUNT);

    	if (gpNamespace.UsePropBeforeInfo.GOODRESTCOUNT > 0) {
    		gpNamespace.UsePropBeforeInfo.ISUSEPROP = true;
    		tyNamespace.addWaitLayer();
    		ht.netManager.useProp(57, 0);
    	}
    	else {
    		gpNamespace.UsePropBeforeInfo.ISUSEPROP = false;
    		gpNamespace.addJumpLayer(xzgbNamespace.JumpType.Xuezhan, this.xuezhanCallback, this);
    	}
    },

    onEnterTransitionDidFinish: function () {
        this._super();

        if (gpNamespace.subRoom > 4)
            return;

        var self = this.self;

        if (!self.isHide)
            this.scheduleOnce(self.yincangCallbackFunction, 5);
    },

    yincangCallbackFunction: function () {
        var self = this.self;

        var action1 = cc.moveBy(0.5, -269, 0);

//        self.missionInMenu.setVisible(false);

//        self.isHide = true;

//        self.missionSprite.runAction(action1.easing(cc.easeBackOut()));

//        self.scheduleOnce(function () {
//            self.missionOutMenu.setVisible(true);
//        }, 0.3)
    },

    missionOutCallbackFunction: function (sender) {
        cc.log("任务出现");

        //gpNamespace.playEffect(gpNamespace.soundRes.ButtonEffect, false);

        tyNamespace.setMenuEnable(sender);

        var self = this.self;

        var action1 = cc.moveBy(0.5, 269, 0);

        self.missionOutMenu.setVisible(false);

        self.missionSprite.runAction(action1.easing(cc.easeBackIn()));

        self.scheduleOnce(function () {
            self.isHide = false;
            self.missionInMenu.setVisible(true);
        }, 0.5)
    },

    missionInCallbackFunction: function (sender) {
        cc.log("任务隐藏");

        //gpNamespace.playEffect(gpNamespace.soundRes.ButtonEffect, false);

        tyNamespace.setMenuEnable(sender);

        var self = this.self;

        var action1 = cc.moveBy(0.5, -269, 0);

        self.missionInMenu.setVisible(false);

        self.missionSprite.runAction(action1.easing(cc.easeBackOut()));

        self.scheduleOnce(function () {
            self.isHide = true;
            self.missionOutMenu.setVisible(true);
        }, 0.3)
    },

    //游戏内部循环 
    getMissionData: function (index) {
//        xinyou.netManager.myMission(2, 1, index);
    },

    settingCallBackFunction: function (sender) {
        cc.log("设置");

        //gpNamespace.playEffect(gpNamespace.soundRes.ButtonEffect, false);

        tyNamespace.setMenuEnable(sender);

        sender.runAction(cc.sequence(cc.scaleTo(0.1, 1.02, 0.98), cc.scaleTo(0.1, 0.98, 1.02), cc.scaleTo(0.1, 1, 1), cc.callFunc(function () {
            var runningScene = cc.director.getRunningScene();
            var tyModelLayer1 = new gpNamespace.TyModelLayer1();
            var tyModelLayer = new gpNamespace.TyModelLayer();
            tyModelLayer.setTouchArea(cc.size(450, 133), cc.p(410, 380));
            tyModelLayer1.addChild(tyModelLayer);
            runningScene.addChild(tyModelLayer1, 10, "innerGameSetting");
            //this.addChild(tyModelLayer, 10);

            var tyGameSettingLayer = new gpNamespace.TyGameSettingLayer();
            tyGameSettingLayer.attr({
                x: 0,
                y: cc.winSize.height
            });
            tyModelLayer.addChild(tyGameSettingLayer);

            tyGameSettingLayer.runAction(cc.moveBy(20 / 60, cc.p(0, -cc.winSize.height)).easing(cc.easeBackOut()));
        }, this)));
    },

    talkCallFunction: function (sender) {
        cc.log("说话");

        //按钮音效特效
        //gpNamespace.playEffect(gpNamespace.soundRes.ButtonEffect, false);

        tyNamespace.setMenuEnable(sender);

        var scaleSmall = new cc.ScaleTo(5 / 60, 0.95, 0.95);
        var scaleBig = new cc.ScaleTo(5 / 60, 1, 1);
        var clickAction = new cc.Sequence(scaleSmall, scaleBig);

        clickAction.easing(cc.easeCircleActionInOut());
        sender.runAction(clickAction);

        var runningScene = cc.director.getRunningScene();
        var tyModelLayer1 = new gpNamespace.TyModelLayer1();
        var tyModelLayer = new gpNamespace.TyModelLayer();
        tyModelLayer.setTouchArea(cc.size(667, 385), cc.p(317, 0));
        tyModelLayer1.addChild(tyModelLayer);
        runningScene.addChild(tyModelLayer1, 10);

        var messageLayer = new gpNamespace.MessageLayer();
        messageLayer.attr({
            x: 0,
            y: -cc.winSize.height
        });
        tyModelLayer.addChild(messageLayer);

        messageLayer.runAction(cc.moveBy(20 / 60, cc.p(0, cc.winSize.height)).easing(cc.easeSineOut()));
    },

    addBeiShu: function (bei) {
//        var beiShu = this.getChildByName("topBack").getChildByName("beiShu");
//
//        if (beiShu) {
//            gpNamespace.NetManager.getInstance().bei *= bei;
//
//            beiShu.reloadNum(gpNamespace.NetManager.getInstance().bei);
//        }
    },

    jiPaiCallbackFunction: function (sender) {
        //gpNamespace.playEffect(gpNamespace.soundRes.ButtonEffect, false);

        tyNamespace.setMenuEnable(sender);

        if (this.getChildByTag(3))
            return;

        var remainsShow = this.getChildByName("remainsShow");
        if (remainsShow) {
            this.removeChild(remainsShow);
            return;
        }

        xinyou.netManager.pokeCount(1);

        //remainsShow = new cc.Sprite("#ddz_jpq_002u.png");
        //remainsShow.attr({
        //    x: 640,
        //    y: 111
        //});
        //this.addChild(remainsShow, 10, "remainsShow");
        //
        //this.updateCardsRemain();
    },

    updateCardsRemain: function () {
        var remainsShow = this.getChildByName("remainsShow");
        if (!remainsShow)
            return;

        remainsShow.removeAllChildren(true);

        var players = gpNamespace.NetManager.getInstance().players;

        var remainTiles = [];
        for (var i = 1; i < 16; i++) {
            remainTiles[i] = 4;
            if (i > 13)
                remainTiles[i] = 1;
        }

        for (var i = 0; i < players.length; i++) {
            var player = players[i];
            var unusedTiles = player.tableTiles;
            for (var j = 0; j < unusedTiles.length; j++) {
                var tile = unusedTiles[j];
                remainTiles[tile.num]--;
            }
        }

        for (var i = 1; i < 16; i++) {
            var remainCard = remainTiles[i];
            cc.log("num:" + i + ",remain:" + remainCard);

            if (remainCard < 0 || remainCard > 4)
                continue;

            var imageName = "#ddz_jpq_0" + remainCard + "u.png";
            var numNode = new cc.Sprite(imageName);
            numNode.setPosition(718 - (i - 1) * 46, 36);
            remainsShow.addChild(numNode, 10, "numNode");
        }
    },

    directShowLastThree: function (tiles) {
        var threeCardLayer = this.getChildByName("threeCardLayer");
        threeCardLayer.removeAllChildren(true);
        this.dipai = tiles;

        this.armature.removeFromParent(false);

        var threeCardLayer = this.getChildByName("threeCardLayer");

        var lastCardStartX = 575;

        for (var int = 0; int < this.dipai.length; int++) {
            cc.log("tiles" + this.dipai[int].num + this.dipai[int].type);
        }

        for (var i = 0; i < 3; i++) {
            var tile = this.dipai[i];
            tile.setStatus(gpNamespace.TileStatus.Zhua);

            var lastCard = new cc.Sprite(tile.img);
            lastCard.setPosition(lastCardStartX + i * 64, 686);
            threeCardLayer.addChild(lastCard);
        }

        for (var i = 0; i < this.orderedPlayers.length; i++) {
            var player = this.orderedPlayers[i];

            var playLayer = player.playLayer;

//            var diZhuImg = "#ddz_rw_006u.png";

            if (player.orderIndex != this.zhuangIndex) {
                diZhuImg = "#ddz_rw_005u.png";
            }

            var diZhuNode = new cc.Sprite(diZhuImg);

            diZhuNode.setPosition(12, 120);
            playLayer.myHeadNode.addChild(diZhuNode, 1, 5);

            var grabImage = playLayer.myHeadNode.getChildByName("grabImage");
            if (grabImage)
                grabImage.removeFromParent(true);
        }

        this.removeChildByTag(2);
    },

    clearBackThree: function () {
        var threeCardLayer = this.getChildByName("threeCardLayer");
        threeCardLayer.removeAllChildren(true);
    },

    showLastThree: function (tiles) {
    	cc.log("showLastThree");
    	
//        this.clearBackThree();
//        this.dipai = tiles;
//
//        for (var int = 0; int < tiles.length; int++) {
//            cc.log("tiles" + tiles[int].num + tiles[int].type);
//        }
//
//        //亮底牌动画
//        var armature = new ccs.Armature("ddz_04u_01a");
//        armature.getAnimation().playWithIndex(0);
//        armature.getAnimation().setSpeedScale(1);
//        armature.setScale(1);
//        armature.setAnchorPoint(0.5, 0.5);
//        armature.setPosition(639, 685);
//        this.addChild(armature, 2);
//        this.armature = armature;
//        this.scheduleOnce(this.showDipaiAndReload, 1);
    },

    showDipaiAndReload: function () {
    	cc.log("showDipaiAndReload");
    	
        this.armature.removeFromParent(false);

        this.showDipai();

        var zhuang = this.getPlayerByOrderIndex(this.zhuangIndex);

        if (this.zhuangIndex == 0 || zhuang.isShowCards)
            zhuang.playLayer.reloadTiles(this.dipai);
        else
            zhuang.playLayer.reloadRemains(3, true);
    },

    showDipai: function () {
        var threeCardLayer = this.getChildByName("threeCardLayer");

        var lastCardStartX = 575;

        for (var int = 0; int < this.dipai.length; int++) {
            cc.log("tiles" + this.dipai[int].num + this.dipai[int].type);
        }

        for (var i = 0; i < 3; i++) {
            var tile = this.dipai[i];
            tile.setStatus(gpNamespace.TileStatus.Zhua);

            var lastCard = new cc.Sprite(tile.img);
            lastCard.setPosition(lastCardStartX + i * 64, 686);
            threeCardLayer.addChild(lastCard);
        }

        for (var i = 0; i < this.orderedPlayers.length; i++) {
            var player = this.orderedPlayers[i];

            var playLayer = player.playLayer;

            var diZhuImg = "#ddz_rw_006u.png";

            if (player.orderIndex != this.zhuangIndex) {
                diZhuImg = "#ddz_rw_005u.png";
            }

            var diZhuNode = new cc.Sprite(diZhuImg);

            diZhuNode.setPosition(12, 120);
            playLayer.myHeadNode.addChild(diZhuNode, 1, 5);

            var grabImage = playLayer.myHeadNode.getChildByName("grabImage");
            if (grabImage)
                grabImage.removeFromParent(true);
        }
    },

    hold: function (player, playerStatus, time) {
        player.status = playerStatus;

        cc.log("gpNamespace.holdTime.v" + playerStatus);

        if (time == null) {
            time = gpNamespace.getMessage("gpNamespace.holdTime.v" + playerStatus)
        }

        cc.log("time" + time);
        this.holdAt = player;
        this.scheduleOnce(this.checkHold, time);
    },

    checkHold: function () {
        cc.log("checkHold:" + this.holdAt == null || (this.holdAt.status != gpNamespace.PlayerStatus.GetHold && this.holdAt.status == gpNamespace.PlayerStatus.ChuHold));
        this.unCheckHold();

        if (this.holdAt == null || (this.holdAt.status != gpNamespace.PlayerStatus.GetHold && this.holdAt.status == gpNamespace.PlayerStatus.ChuHold))
            return;

        if (this.holdAt.orderIndex == 0) {
            this.holdAt.status = gpNamespace.PlayerStatus.Pass;
            this.holdAt.playLayer.addTrustMenu();
            this.holdAt.playLayer.removeActionsLayer();
        }

        this.holdAt = null;
    },

    unCheckHold: function () {
        cc.log("unCheckHold：" + this.holdAt);
        this.unschedule(this.checkHold);
    },

    //设置当前玩家
    setCurrentPlayer: function (player) {
        if (this.currentAt != null) {
            this.timeLayer&&this.timeLayer.setCurrentPosition(player.orderIndex);
        }

        this.currentAt = player;
    },

    getPlayerByOrderIndex: function (orderIndex) {
        return gpNamespace.NetManager.getInstance().getPlayerByChairID(orderIndex);
    },

    drawScores: function (opreationScore) {
        for (var i = 0; i < opreationScore.length; i++) {
            var score = opreationScore[i];
            var player = this.getPlayerByOrderIndex(i);

            if (score != 0)
                player.playLayer.drawScoreLayer(score);
        }
    },

    onExit: function () {
        this.removeAllChildren(true);
        this._super();
    }
});